package org.dbstar.scheduler.control.db.job;

import java.sql.Types;
import java.util.Map;

import net.sf.json.JSONSerializer;

import org.dbstar.scheduler.beans.Job;
import org.dbstar.scheduler.identifier.Identifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;


/**
 * 快速插入Job对象
 * 
 * @author 代波
 * @since 1.0.0
 * @version 1.0.0
 * @date 2012-4-28
 */
public class JobInsert extends SimpleJdbcInsert {
	public JobInsert(JdbcTemplate jdbcTemplate) {
		super(jdbcTemplate);
		withTableName("SCHD_JOB");
		usingColumns("SYSTEM_IDENTIFIER", "SEQUENCE", "IDENTIFIER", "CONF_SYSTEM_IDENTIFIER", "CONF_SEQUENCE",
				"CONF_IDENTIFIER", "TYPE", "STATUS", "RESOURCE", "CONTENT", "PARAMETER_SIZE", "PARAMETER_DATA",
				"SUBMIT_TIME", "LAUNCH_TIME", "FINISH_TIME", "RESULT", "READY", "SUCCEED", "RETRY", "MAX_RETRY",
				"SUBMITTER");
	}

	public int insertJob(Job job, Identifier identifier) {
		MapSqlParameterSource source = new MapSqlParameterSource();
		source.addValue("SYSTEM_IDENTIFIER", identifier.getSystemIdentifier(), Types.VARCHAR);
		source.addValue("SEQUENCE", identifier.getSequence(), Types.INTEGER);
		source.addValue("IDENTIFIER", identifier.getStringIdentifier(), Types.VARCHAR);
		source.addValue("CONF_SYSTEM_IDENTIFIER", job.getJobConfIdentifier().getSystemIdentifier(), Types.VARCHAR);
		source.addValue("CONF_SEQUENCE", job.getJobConfIdentifier().getSequence(), Types.INTEGER);
		source.addValue("CONF_IDENTIFIER", job.getJobConfIdentifier().getStringIdentifier(), Types.VARCHAR);
		source.addValue("TYPE", job.getType(), Types.VARCHAR);
		source.addValue("STATUS", job.getStatus().name(), Types.VARCHAR);
		source.addValue("RESOURCE", job.getResource(), Types.VARCHAR);
		source.addValue("CONTENT", job.getContent(), Types.VARCHAR);
		source.addValue("PARAMETER_SIZE", job.getParameterSize(), Types.INTEGER);
		source.addValue("PARAMETER_DATA", parseParametersJson(job.getParameters()), Types.VARCHAR);
		source.addValue("SUBMIT_TIME", job.getSubmitTime(), Types.BIGINT);
		source.addValue("LAUNCH_TIME", job.getLaunchTime(), Types.BIGINT);
		source.addValue("FINISH_TIME", job.getFinishTime(), Types.BIGINT);
		source.addValue("RESULT", job.getResultString(), Types.VARCHAR);
		source.addValue("READY", job.isReady(), Types.BOOLEAN);
		source.addValue("SUCCEED", job.isSucceed(), Types.BOOLEAN);
		source.addValue("RETRY", job.getRetry(), Types.INTEGER);
		source.addValue("MAX_RETRY", job.getMaxRetry(), Types.INTEGER);
		source.addValue("SUBMITTER", job.getSubmitter(), Types.VARCHAR);
		return super.execute(source);
	}

	private String parseParametersJson(Map<String, String> parameters) {
		if (parameters == null || parameters.isEmpty()) {
			return null;
		} else {
			return JSONSerializer.toJSON(parameters).toString();
		}
	}
}
